<template>
  <div class="order-confirm">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="container">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>订单确认</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div class="container" v-loading="loading">
      <div class="order-content" v-if="orderInfo">
        <!-- 收货地址 -->
        <el-card class="address-card" shadow="never">
          <template #header>
            <div class="card-header">
              <el-icon><Location /></el-icon>
              <span>收货地址</span>
            </div>
          </template>

          <AddressSelector v-model="selectedAddress" />
        </el-card>

        <!-- 商品信息 -->
        <div class="goods-section">
          <h3>商品信息</h3>
          <div class="goods-list">
            <div v-for="item in orderInfo.items" :key="item.productId" class="goods-item">
              <div class="goods-image">
                <img :src="item.productImage || '/placeholder.svg'" :alt="item.productName" />
              </div>
              <div class="goods-info">
                <h4>{{ item.productName }}</h4>
                <p v-if="item.skuSpecifications" class="goods-spec">
                  {{ formatSpecifications(item.skuSpecifications) }}
                </p>
                <div class="goods-price">
                  <span class="price">¥{{ item.price }}</span>
                  <span class="quantity">x{{ item.quantity }}</span>
                </div>
              </div>
              <div class="goods-total">
                ¥{{ item.totalAmount }}
              </div>
            </div>
          </div>
        </div>

        <!-- 配送方式和订单备注 -->
        <el-card class="delivery-card" shadow="never">
          <el-form
            ref="orderFormRef"
            :model="orderForm"
            :rules="orderRules"
            label-width="80px"
          >
            <el-form-item label="配送方式" prop="deliveryMethod">
              <el-radio-group v-model="orderForm.deliveryMethod">
                <el-radio value="standard">标准配送（免费）</el-radio>
                <el-radio value="express">快速配送（+10元）</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="订单备注">
              <el-input
                v-model="orderForm.remark"
                type="textarea"
                :rows="3"
                placeholder="选填，请输入订单备注"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 费用明细 -->
        <div class="cost-section">
          <h3>费用明细</h3>
          <div class="cost-details">
            <div class="cost-item">
              <span>商品总价</span>
              <span>¥{{ orderInfo.goodsAmount }}</span>
            </div>
            <div class="cost-item">
              <span>运费</span>
              <span>¥{{ orderInfo.shippingFee }}</span>
            </div>
            <div class="cost-item" v-if="orderInfo.pointsAmount > 0">
              <span>积分抵扣</span>
              <span class="discount">-¥{{ orderInfo.pointsAmount }}</span>
            </div>
            <div class="cost-item total">
              <span>应付总额</span>
              <span class="total-price">¥{{ totalAmount }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作栏 -->
      <div class="order-footer" v-if="orderInfo">
        <div class="footer-content">
          <div class="total-info">
            <span class="total-text">应付总额：</span>
            <span class="total-price">¥{{ totalAmount }}</span>
          </div>
          <div class="footer-actions">
            <el-button size="large" @click="goBack">返回</el-button>
            <el-button type="primary" size="large" @click="submitOrder" :loading="loading">
              提交订单
            </el-button>
          </div>
        </div>
      </div>

      <!-- 订单信息不存在 -->
      <div class="no-order" v-if="!loading && !orderInfo">
        <el-empty description="订单信息不存在">
          <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Location } from '@element-plus/icons-vue'
import { useOrderStore } from '@/stores/order'
import { useUserStore } from '@/stores/user'
import { orderApi } from '@/api/order'
import AddressSelector from '@/components/AddressSelector.vue'
import type { Address } from '@/api/address'

const router = useRouter()
const orderStore = useOrderStore()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const orderFormRef = ref<FormInstance>()
const selectedAddress = ref<Address | null>(null)

// 表单数据
const orderForm = reactive({
  deliveryMethod: 'standard',
  remark: ''
})

// 表单验证规则
const orderRules: FormRules = {
  deliveryMethod: [
    { required: true, message: '请选择配送方式', trigger: 'change' }
  ]
}

// 计算属性
const orderInfo = computed(() => orderStore.orderInfo)

const totalAmount = computed(() => {
  if (!orderInfo.value) return 0
  return orderInfo.value.goodsAmount + orderInfo.value.shippingFee - orderInfo.value.pointsAmount
})

// 方法
const formatSpecifications = (specs: any) => {
  if (!specs || typeof specs !== 'object') return ''
  return Object.entries(specs).map(([key, value]) => `${key}: ${value}`).join(', ')
}

const goBack = () => {
  router.go(-1)
}

const submitOrder = async () => {
  if (!orderFormRef.value) return

  try {
    // 验证用户登录状态
    if (!userStore.userInfo?.userId) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }

    // 验证地址
    if (!selectedAddress.value) {
      ElMessage.error('请选择收货地址')
      return
    }

    await orderFormRef.value.validate()

    if (!orderInfo.value) {
      ElMessage.error('订单信息不存在')
      return
    }

    loading.value = true

    // 构建订单数据
    const orderData = {
      userId: userStore.userInfo!.userId,  // 已经验证过用户登录状态，可以直接使用
      items: orderInfo.value.items.map(item => ({
        productId: item.productId,
        skuId: item.skuId,
        quantity: item.quantity,
        price: item.price
      })),
      consigneeName: selectedAddress.value.receiverName,
      consigneePhone: selectedAddress.value.receiverPhone,
      consigneeAddress: selectedAddress.value.fullAddress,
      buyerMessage: orderForm.remark || '',  // 修改字段名为 buyerMessage
      shippingFee: 0,  // 添加运费字段
      pointsAmount: 0  // 添加积分抵扣字段
    }

    console.log('提交订单数据:', orderData)

    // 调用API创建订单
    const response = await orderApi.createOrder(orderData)

    ElMessage.success('订单创建成功')

    // 清空订单信息
    orderStore.clearOrderInfo()

    // 跳转到支付页面
    router.push(`/order/pay/${response.data.orderId}`)

  } catch (error) {
    console.error('提交订单失败:', error)
    ElMessage.error('提交订单失败，请重试')
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  // 检查是否有订单信息
  if (!orderInfo.value) {
    ElMessage.error('订单信息不存在，请重新下单')
    router.push('/')
  }
})
</script>

<style scoped>
.order-confirm {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 100px;
}

.address-card,
.delivery-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.breadcrumb {
  background: white;
  padding: 15px 0;
  border-bottom: 1px solid #e0e0e0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.order-content {
  margin: 20px 0;
}

.address-section,
.goods-section,
.shipping-section,
.remark-section,
.cost-section {
  background: white;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.address-section h3,
.goods-section h3,
.shipping-section h3,
.remark-section h3,
.cost-section h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  border-bottom: 2px solid #ff6900;
  padding-bottom: 10px;
}

/* 商品列表 */
.goods-list {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border-radius: 8px;
  overflow: hidden;
}

.goods-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-info {
  flex: 1;
}

.goods-info h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.goods-spec {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.goods-price {
  display: flex;
  align-items: center;
  gap: 10px;
}

.goods-price .price {
  font-size: 16px;
  font-weight: 600;
  color: #ff6900;
}

.goods-price .quantity {
  font-size: 14px;
  color: #666;
}

.goods-total {
  font-size: 18px;
  font-weight: 600;
  color: #ff6900;
}

/* 配送方式 */
.shipping-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 15px 0;
}

.shipping-info strong {
  display: block;
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.shipping-info p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.shipping-fee {
  font-size: 16px;
  font-weight: 600;
  color: #ff6900;
}

/* 费用明细 */
.cost-details {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
}

.cost-item:last-child {
  border-bottom: none;
}

.cost-item.total {
  background: #f8f9fa;
  font-weight: 600;
}

.cost-item .discount {
  color: #67c23a;
}

.cost-item .total-price {
  font-size: 18px;
  color: #ff6900;
}

/* 底部操作栏 */
.order-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-top: 1px solid #e0e0e0;
  padding: 15px 0;
  z-index: 100;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.total-text {
  font-size: 16px;
  color: #333;
}

.footer-content .total-price {
  font-size: 24px;
  font-weight: 600;
  color: #ff6900;
}

.footer-actions {
  display: flex;
  gap: 15px;
}

/* 空状态 */
.no-order {
  background: white;
  padding: 60px 20px;
  margin: 20px 0;
  border-radius: 8px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }

  .goods-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .goods-image {
    align-self: center;
  }

  .goods-total {
    align-self: flex-end;
  }

  .footer-content {
    flex-direction: column;
    gap: 15px;
  }

  .footer-actions {
    width: 100%;
    justify-content: center;
  }
}
</style>
